package com.starlink.databaseservice.mongo;

import com.alibaba.fastjson2.JSONObject;
import com.starlink.databaseservice.model.Post;
import com.starlink.databaseservice.model.User;
import com.starlink.databaseservice.repository.PostRepository;
import com.starlink.databaseservice.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.bson.json.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonComponentModule;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service
@Slf4j
public class PostsService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private JsonComponentModule jsonComponentModule;
    @Autowired
    private PostRepository postRepository;

    public void load() {
        int start = 0;
        int limit = 1000;
        for (start = 25; start < 120; start++) {
            test(start * limit, limit);
        }
    }

    public void test(int start, int limit) {
        log.info("start is: {}, limit is: {}", start, limit);
        Query query = new Query();
        Set<User> userSet = new HashSet<>();
        List<Post> postList = new ArrayList<>();
        query.skip(start);
        query.limit(limit);
        List<JSONObject> jsonObjects = mongoTemplate.find(query, JSONObject.class, "posts");
//        log.info("result is:{}", jsonObjects);
        for (JSONObject jsonObject : jsonObjects) {
            JSONObject postUser = jsonObject.getJSONObject("post_user");
//            log.info("post user is: {}", postUser.toJSONString());
            userSet.add(getUserInfo(postUser));
            postList.add(getPostInfo(jsonObject));

            JSONObject replyJson = jsonObject.getJSONObject("reply_list");
            if (replyJson != null && !replyJson.isEmpty()){
                log.info("reply json is: {}", replyJson.toJSONString());
            }

        }
        try {
            userRepository.saveAll(userSet);
        }catch (Exception exception) {

        }
        postRepository.saveAll(postList);


    }


    private Post getPostInfo(JSONObject postJson) {
        String mongoId = postJson.getString("_id");
        String code = postJson.getString("code_name");
        String simpleCode = "";
        if (StringUtils.hasLength(code) && code.length() > 6)
            simpleCode = code.substring(0,6);
        Long userId = postJson.getJSONObject("post_user").getLong("user_id");
        String postFrom = postJson.getString("post_from");
        String postTitle = postJson.getString("post_title");
        String postContent = postJson.getString("post_content");
        Integer contentType = postJson.getInteger("content_type");
        Date postLastTime = postJson.getDate("post_last_time");
        Date pubishTime = postJson.getDate("post_publish_time");
        Integer clickCount = postJson.getInteger("post_click_count");
        Integer postCommentCount = postJson.getInteger("post_comment_count");
        Integer postLikeCount = postJson.getInteger("post_like_count");
        Long postId = postJson.getLong("post_id");
        String postSourceId = postJson.getString("post_source_id");
        return Post.builder()
                .mongoId(mongoId)
                .code(code)
                .simpleCode(simpleCode)
                .postUserId(userId)
                .postFrom(postFrom)
                .postTitle(postTitle)
                .postContent(postContent)
                .contentType(contentType)
                .postLastTime(postLastTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())
                .postPublishTime(pubishTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())
                .postClickCount(clickCount)
                .postCommentCount(postCommentCount)
                .postLikeCount(postLikeCount)
                .postId(postId)
                .postSourceId(postSourceId)
                .build();
    }

    /**
     * 获取用户的信息
     * @param postUserJson
     * @return
     */
    private User getUserInfo(JSONObject postUserJson) {
        Long userId = postUserJson.getLong("user_id");
        String nickName = postUserJson.getString("user_nickname");
        String userName = postUserJson.getString("user_name");
        Integer userV = postUserJson.getInteger("user_v");
        Integer userType = postUserJson.getInteger("user_type");
        Boolean maJia = postUserJson.getBoolean("user_is_majia");
        Double userAge = Double.valueOf(postUserJson.getString("user_age").replace("年","").replace("月","").replace("天","").replace("个",""));
        return User.builder()
                .userId(userId)
                .nickName(nickName)
                .userName(userName)
                .userV(userV)
                .userType(userType)
                .userIsMaJia(maJia)
                .userAge(userAge)
                .build();
    }
}
